import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../../shared/smartadmin.config'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-car-authentication',
  templateUrl: './car-authentication.component.html',
  styleUrls: ['./car-authentication.css']
})
export class CarAuthenticationManageComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableParam: any = {
    phone: '',
    name: '',
    carNumber: '',
    companyId: '',
    auditWay: '',
    auditStatus: '',
    searchKey: ''
  }
  deviceControlFrom: any = {
    id: '',
    auditStatus: '3'
  }
  phoneList: any = []
  nameList: any = []
  isShowAdd: boolean = false
  isShowDel: boolean = false
  jumpData: any // 跳转页面接收到的数据
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
      if (common.getCookie('carDetail')) {
        this.jumpData = JSON.parse(common.getCookie('carDetail'))
        common.clearCookie('carDetail')
      }
    })
  }
  ngOnInit() {
    if (this.jumpData) {
      this.tableParam.phone = this.jumpData.phone
      this.tableParam.carNumber = this.jumpData.carNumber
    }
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initPhone()
      })
    })
    System.import('assets/js/viewer/viewer.js').then(() => {
      System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
        System.import('assets/js/viewer/viewer.css').then(() => {})
      })
    })
    this.load()
  }

  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        ...this.tableParam
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('appletBandingCarAudit/findBandingCarAudit.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        // data.exhibitDatas[0].carHeadImg =data.exhibitDatas[0].userPhoto
        // data.exhibitDatas[0].drivingPermitOneImg =data.exhibitDatas[2].userPhoto
        // data.exhibitDatas[0].drivingPermitTwoImg =data.exhibitDatas[3].userPhoto
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //公司选中回调
  companySelected(data) {
    this.tableParam.companyName = data.companyName
    this.tableParam.companyId = data.companyId
  }

  //初始化车辆
  initPhone() {
    var that = this
    $('#carNumberSelect2').val(this.tableParam.carNumber)
    //认证人员
    $('#nameSelect2')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 1,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'appointmentRepairCar/findQueryParam.html',
          dataType: 'json',
          delay: 100,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              param: params.term,
              type: 2
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, car) {
              options.push({
                id: car.id,
                text: car.name
              })
            })
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa  fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.name = data.text
      })
    //手机号码
    $('#phoneSelect2')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 1,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'appointmentRepairCar/findQueryParam.html',
          dataType: 'json',
          delay: 100,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              param: params.term,
              type: 1
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, car) {
              options.push({
                id: car.id,
                text: car.phone
              })
            })
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-mobile-phone green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.phone = data.text
      })
    //车辆
    $('#carNumberSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
        ajax: {
          url: config.BaseURL + 'stats/carListByCarNumber.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              carNumber: params.term // search term
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            // 小于10个数量才判断重复
            if (data.data.length <= 10) {
              let arr = []
              let sameCar = []
              // 判断相同的车牌号
              for (let index = 0; index < data.data.length; index++) {
                let car = data.data[index]
                if (arr.indexOf(car.carNumber) != -1) {
                  sameCar.push(car.carNumber)
                } else {
                  arr.push(car.carNumber)
                }
              }
              $(data.data).each(function (index, car) {
                if (sameCar.indexOf(car.carNumber) != -1) {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber + '[' + car.parentName + ']'
                  })
                } else {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber
                  })
                }
              })
            } else {
              $(data.data).each(function (index, car) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber
                })
              })
            }
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.carNumber = data.text
        if (data.text.indexOf('[') > 0) {
          that.tableParam.carNumber = data.text.split('[')[0]
        } else {
          that.tableParam.carNumber = data.text
        }
      })

    var phoneOption = new Option(this.tableParam.phone, this.tableParam.phone, true, true)
    $('#phoneSelect2').append(phoneOption)
    var carNumberOption = new Option(this.tableParam.carNumber, this.tableParam.carNumber, true, true)
    $('#carNumberSelect2').append(carNumberOption)
  }
  delPhone() {
    this.tableParam.phone = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#phoneSelect2').val('')
    $('#select2-phoneSelect2-container').empty()
    $('#select2-phoneSelect2-container').attr('title', '')
    $('#select2-phoneSelect2-container').prepend(str)
  }
  delName() {
    this.tableParam.name = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#nameSelect2').val('')
    $('#select2-nameSelect2-container').empty()
    $('#select2-nameSelect2-container').attr('title', '')
    $('#select2-nameSelect2-container').prepend(str)
  }
  //清除车辆选中值
  delCarNumber() {
    this.tableParam.deviceId = ''
    this.tableParam.carNumber = ''
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#carNumberSelect2').val('')
    $('#select2-carNumberSelect2-container').empty()
    $('#select2-carNumberSelect2-container').attr('title', '')
    $('#select2-carNumberSelect2-container').prepend(str)
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  imgInfo: any = []
  isViewer: boolean = false //默认隐藏
  //查看照片
  open_img(row, val, str) {
    val.show()
    var imgList = row[str].split(',')
    this.imgInfo = []
    for (var b = 0; b < imgList.length; b++) {
      // let localImg;
      // if(imgList[b][0] == '/'){
      // 	localImg = config.BaseURL + imgList[b].substr(1);
      // }else{
      // 	localImg = config.BaseURL + imgList[b];
      // }
      let localImg
      if (imgList[b].indexOf('http') == -1) {
        if (imgList[b][0] == '/') {
          localImg = config.BaseURL + imgList[b].substr(1)
        } else {
          localImg = config.BaseURL + imgList[b]
        }
      } else {
        localImg = imgList[b]
      }

      this.imgInfo.push(localImg)
      // this.imgInfo.push(imgList[b]);
    }
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }

  imgClose(modal) {
    modal.hide()
  }
  bigImg: any = '' // 放大的图片
  //图片放大
  bigimg(modal, row) {
    // modal.show();
    this.bigImg = row
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  //显示图片组件
  viewer: any = ''
  showImg() {
    var that = this
    var imgList = $('.imagesInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
  CloseBigImg(modal) {
    modal.hide()
  }

  /*
   * 审核
   */
  auditStatusRow(row, modal) {
    modal.show()
    this.deviceControlFrom.id = row.id
  }

  auditStatusChange(val) {
    this.deviceControlFrom.auditStatus = val
  }

  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
    this.deviceControlFrom.auditStatus = '3'
  }
  /*
   * form提交
   */
  deviceControlSubmit(modal) {
    let url = 'appletBandingCarAudit/check.html'
    this.jsonApiService.http_obj(url, this.deviceControlFrom).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        this.modalClose(modal)
      }
    })
  }
  //删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http_obj('appletBandingCarAudit/deleteById.html', { id: row.id }).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
}
